<template>
  <view class="container">
    <custom-status-bar></custom-status-bar>
    <!-- 顶部导航 -->
    <view class="header">
      <view class="back-icon" @click="goBack">
        <uni-icons type="left" size="20" color="#666"></uni-icons>
        <text>返回</text>
      </view>
      <!-- 	  <uni-search-bar class="search-bar" v-model="keyword" cancelButton="none" @confirm="search" @input="handleSearch" ></uni-search-bar>
	    <text class="cancel-btn" @click="clearSearch">取消</text> -->
      <uv-search shape="square" placeholder="请输入搜索内容" v-model="keyword" :clearabled="true" :showAction="true"
        actionText="取消" :animation="true" @search="onSearch" @custom="onCancel"></uv-search>
    </view>
    <!-- 最近搜索历史 -->
    <view class="filter-tags">
      <view v-for="(tag, index) in searchHistory" :key="index" class="filter-tag">
        <text @click="Search(tag)">{{ tag }}</text>
        <text class="close-btn" @click="removeFilter(index)">×</text>
      </view>
    </view>
    <!-- 清除历史 -->
    <view class="clear-history" @click="clearAllFilters" v-if="searchHistory.length > 0"> 清除所有搜索历史 </view>
    <!--  搜索结果  商品列表 -->
    <view class="product-list">
      <view v-for="product in result" :key="product.id" class="product-item" @click="gotoDetail(product.pid)">
        <image :src="product.smallImg" class="product-image" />
        <view class="product-name">{{ product.name }}</view>
        <view class="product-english">{{ product.enname }}</view>
        <view class="product-price">¥{{ product.price }}</view>
      </view>
    </view>
  </view>
</template>
<script setup>
import CustomStatusBar from '../../components/common/CustomStatusBar.vue';
import {
  ref,
  onMounted
} from 'vue';
import {
  onLoad
} from '@dcloudio/uni-app';
import {
  searchProduct
} from "@/api/index.js";
import {
  saveSearchKeyword
} from "@/tools/index.js"
// 响应式搜索关键词
const keyword = ref('');
// 搜索结果
const result = ref([]);

const searchHistory = ref([]);

// 页面加载钩子
onLoad(async (options) => {
  if (options?.query) {
    keyword.value = options.query;
    console.log(" keyword.value :", keyword.value)
    // 执行搜索
    const res = await searchProduct(keyword.value);
    //
    saveSearchKeyword(keyword.value)
    if (res.code === 'Q001') {
      result.value = res.result;
    }
    // nextTick();
  }
});

// 初始化时加载历史记录
onMounted(() => {
  loadSearchHistory();

  // 监听本地更新事件
  uni.$on('searchHistoryUpdated', (history) => {
    searchHistory.value = history;
  });

  // 监听storage变化（H5专属）
  uni.$on('storage', (res) => {
    if (res.key === 'searchHistory') {
      loadSearchHistory();
    }
  });


});

// 从storage加载到响应式变量
const loadSearchHistory = () => {
  try {
    const historyStr = uni.getStorageSync('searchHistory');
    searchHistory.value = historyStr ? JSON.parse(historyStr) : [];
  } catch (e) {
    searchHistory.value = [];
  }
};

const Search = async (tag) => {
  if (!tag.trim()) return;
  saveSearchKeyword(tag)
  const res = await searchProduct(tag);
  if (res.code === 'Q001') {
    result.value = res.result;
  }
}


// 搜索
const onSearch = async () => {
  if (!keyword.value.trim()) return;
  saveSearchKeyword(keyword.value)
  const res = await searchProduct(keyword.value);
  if (res.code === 'Q001') {
    result.value = res.result;
  }
}
// 取消
const onCancel = () => {
  keyword.value = ''
}
// 删除单个历史标签
const removeFilter = (index) => {
  if (index < 0 || index >= searchHistory.value.length) return;

  // 移除指定项
  searchHistory.value.splice(index, 1);

  // 持久化存储
  uni.setStorageSync('searchHistory', JSON.stringify(searchHistory.value));

  // 触发全局更新事件
  uni.$emit('searchHistoryUpdated', searchHistory.value);
}
// 清空所有历史
const clearAllFilters = () => {
  searchHistory.value = [];
  uni.setStorageSync('searchHistory', '[]');
  uni.$emit('searchHistoryUpdated', []);
};


const gotoDetail = (pid) => {
  uni.navigateTo({ url: `/pages/detail/detail?pid=${pid}` });
}


// 返回上一页
const goBack = () => {
 const pages = getCurrentPages();
 if (pages.length > 1) uni.navigateBack();
 	else  uni.switchTab({ url: '/pages/index/index' });
};
// 清空搜索（示例方法）
// const clearSearch = () => {
//   uni.navigateBack();
// };
</script>
<style scoped>
.container {
  padding: 0 20rpx;
}

.header {
  display: flex;
  align-items: center;
  height: 100rpx;
  border-bottom: 1rpx solid #eee;
}

.back-icon {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  margin-right: 40rpx;
}

.search-bar {
  display: flex;
  align-items: center;
  background: #F5F5F5;
  border-radius: 40rpx;
  flex: 1;
  padding: 0 20rpx;
}

.search-bar text {
  margin-left: 10rpx;
  font-size: 28rpx;
  color: #666;
}

.cancel-btn {
  margin-left: 20rpx;
  color: #007AFF;
  font-size: 28rpx;
}

.filter-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-top: 20rpx;
}

.filter-tag {
  background: #F5F5F5;
  border-radius: 40rpx;
  padding: 8rpx 20rpx;
  display: flex;
  align-items: center;
}

.close-btn {
  margin-left: 10rpx;
  font-size: 24rpx;
  color: #999;
  cursor: pointer;
}

.clear-history {
  background: #F5F5F5;
  border-radius: 40rpx;
  padding: 20rpx;
  margin-top: 50rpx;
  text-align: center;
  color: #666666;
}

.product-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
  margin-top: 20rpx;
}

.product-item {
  background: white;
  border-radius: 12rpx;
  padding: 20rpx;
  text-align: center;
}

.product-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
  margin: 0 auto 20rpx;
}

.product-name {
  font-size: 28rpx;
  margin-bottom: 10rpx;
  color: #333;
  text-align: left;
}

.product-english {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 20rpx;
  text-align: left;
}

.product-price {
  color: red;
  font-weight: bold;
  font-size: 28rpx;
  text-align: left;
}
</style>